const db = require('../db')

exports.users = (req, res) => {
    let rundb = (sqlStr) => {
        db.query(sqlStr, (err, results) => {
            if (err) return res.cc(err)
            res.send(results)
        })
    }

    if (req.body.set == 'set') { // 添加
        db.query(`SELECT * FROM shujia where username = 'test' and bookid = '${req.body.caricatureId}'`, (err, results) => {
            if (err) return res.cc(err)
            if (results.length != 0) {
                let id = results[0].id;
                db.query(`DELETE FROM shujia WHERE id = ${id}`, (err, results) => {
                    if (err) return res.cc(err)
                    const sqlStr = `insert into shujia (username,bookid,kandao) values ('test','${req.body.caricatureId}','01')`
                    rundb(sqlStr)
                })
            } else {
                const sqlStr = `insert into shujia (username,bookid,kandao) values ('test','${req.body.caricatureId}','01')`
                rundb(sqlStr)
            }
        })
    } else if (req.body.del == 'del') { //删除
        const sqlStr = `DELETE FROM shujia WHERE bookid = '${req.body.bookid}'`
        rundb(sqlStr)
    } else if (req.body.xuigai == 'xuigai') {//修改订阅
        const sqlStr = `update shujia set kandao = '${req.body.hua}' where id = '${req.body.id}'`
        rundb(sqlStr)
    } else if (req.body.inquire == 'inquire') {// 查找特定
        const sqlStr = `SELECT * FROM shujia where username = 'test' and bookid = '${req.body.caricatureId}' `
        rundb(sqlStr)
    } else {
        const sqlStr = `SELECT * FROM shujia where username = 'test'`
        rundb(sqlStr)
    }

}

exports.fenzu = (req, res) => {
    let sqlStr = `SELECT * FROM fengzhu`
    if (req.body.cha == 'cha') {//查组名
        sqlStr = `SELECT * FROM fengzhu where zhumin = '${req.body.zhumin}'`
    } else if (req.body.zhumin != undefined && req.body.bookid != undefined) {//添加分组
        sqlStr = `insert into fengzhu (zhumin,bookid) values ('${req.body.zhumin}','${req.body.bookid}')`
    } else if (req.body.del == 'del') {//删除分组
        sqlStr = `DELETE FROM fengzhu WHERE id = ${req.body.id};`
    } else if (req.body.fengdelbook == "del") {//分组删除/添加书籍
        sqlStr = `update fengzhu set bookid = '${req.body.bookid}' where id = '${req.body.id}'`
    }
    db.query(sqlStr, (err, results) => {
        if (err) return res.cc(err)
        res.send(results)
    })
}